package net.swl.linkedvillage;

import net.swl.linkedvillage.entity.User;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;

public class RegistarActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registar);
		getActionBar().setIcon(R.drawable.logo_linkedvillage);
		setTitle("");
		
		Parse.initialize(this, "VfKri7peCV168zVhdWZBZ8zwZmjZBqWs1GL7Hcoi",
				"0iuOEQKfh6dVM6Y8UYwjAXphYtPchnyEO12jxCyy");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.registar, menu);
		return true;
	}
	
	public void onRegistarClicked(View view) {
		User user = new User();
		
		EditText eTxt = (EditText) findViewById(R.id.editTextUsername);
		String cont = eTxt.getText().toString();
		user.setUsername(cont);
		
		eTxt = (EditText) findViewById(R.id.editTextPassword);
		cont = eTxt.getText().toString();
		user.setPassword(cont);
		
		eTxt = (EditText) findViewById(R.id.editTextEmail);
		cont = eTxt.getText().toString();
		user.setEmail(cont);
		
		eTxt = (EditText) findViewById(R.id.editTextMorada);
		cont = eTxt.getText().toString();
		user.setMorada(cont);
		
		eTxt = (EditText) findViewById(R.id.editTextTelefone);
		cont = eTxt.getText().toString();
		user.setTelefone(cont);
		
		registarUser(user);
		
	}
	
	private void registarUser(User user){
		final ParseUser parseUser = user.getParseObject();
		parseUser.signUpInBackground(new SignUpCallback() {
			@Override
			public void done(ParseException ex) { 
				if (ex == null) {
					onUserRegistered(parseUser);
				} else {
					onRegistFailed(ex);
				}
			}
		});
	}
	
	private void onUserRegistered(ParseUser user) {
		Log.i("registarUser", "User registado");
		Intent i = new Intent(this, RegistoConfirmadoActivity.class);
		startActivity(i);
	}
	
	private void onRegistFailed(ParseException ex) {
		Log.e("registarUser", "Erro no registo do user:" + ex.getMessage());
	}

}
